package com.nari.ncps.screen.service.impl.ne;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.ne.NeProdoperEastPrice;
import com.nari.ncps.screen.mapper.ne.NeProdoperWestPriceMapper;
import com.nari.ncps.screen.service.ne.NeProdoperWestPriceService;
import com.nari.ncps.screen.vo.ne.NeEastElectricPriceVO;
import com.nari.ncps.screen.vo.ne.NeWestElectricPriceVO;
import com.nari.ncps.screen.entity.ne.NeProdoperWestPrice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * <p>
 * 蒙西实时电价表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class NeProdoperWestPriceServiceImpl extends ServiceImpl<NeProdoperWestPriceMapper, NeProdoperWestPrice> implements NeProdoperWestPriceService {

    @Autowired
    private NeProdoperWestPriceMapper neProdoperWestPriceMapper;

    @Override
    public List<NeWestElectricPriceVO> getWestElectricPrice(Integer year) {
        // 如果year为null，使用当前年份
        if (year == null) {
            year = Calendar.getInstance().get(Calendar.YEAR);
        }
        

//        // 按日期分组数据
//        Map<String, Map<Byte, BigDecimal>> dailyDataMap = new HashMap<>();
//        Map<String, Map<String, Object>> dailyMetaData = new HashMap<>(); // 存储完整的日期信息
        // 1. 获取当前年月日
        LocalDate currentDate = LocalDate.now();
        String currentDateStr = currentDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        // 2. 获取前一个月的年月日
        LocalDate previousMonthDate = currentDate.minusMonths(1);
        String previousMonthDateStr = previousMonthDate.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        // 查询指定年份的最新数据
        LambdaQueryWrapper<NeProdoperWestPrice> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(NeProdoperWestPrice::getOrgCode, "02")
                .eq(NeProdoperWestPrice::getDateType, "2")
                .eq(NeProdoperWestPrice::getDelFlag, 0)
                .ge(NeProdoperWestPrice::getStatisticTime, previousMonthDateStr)
                .le(NeProdoperWestPrice::getStatisticTime, currentDateStr);
        queryWrapper.orderByDesc(NeProdoperWestPrice::getDay);

        List<NeProdoperWestPrice> dataList = this.list(queryWrapper);

        // 如果数据库查询结果为空，返回空列表
        if (dataList == null || dataList.isEmpty()) {
            return new ArrayList<>();
        }

        // 按日期分组数据
//        Map<String, Map<Byte, BigDecimal>> dailyDataMap = new HashMap<>();
//        Map<String, Map<String, Object>> dailyMetaData = new HashMap<>(); // 存储完整的日期信息
        // 构建返回结果
        List<NeWestElectricPriceVO> resultList = new ArrayList<>();
        for (NeProdoperWestPrice data : dataList) {
            NeWestElectricPriceVO vo=new NeWestElectricPriceVO();
            vo.setYear(data.getYear());
            vo.setMonth(data.getMonth());
            vo.setDay(data.getDay());
            String date = data.getYear()+"-"+data.getMonth()+"-"+data.getDay();
            // 转换为 LocalDate
            LocalDate localDate = LocalDate.parse(date, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            // 如果需要转换为 java.util.Date
            Date newDate = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
            vo.setDate(newDate);
            vo.setSubsidyPrice(data.getPrice());
            resultList.add(vo);
//        for (Map<String, Object> data : dataList) {
//            Integer dataYear = (Integer) data.get("year");
//            Integer month = (Integer) data.get("month");
//            Integer day = (Integer) data.get("day");
//            Byte priceType = ((Number) data.get("price_type")).byteValue();
//            BigDecimal totalPrice = (BigDecimal) data.get("total_price");
//
//            String key = dataYear + "-" + month + "-" + day;
//            dailyDataMap.computeIfAbsent(key, k -> new HashMap<>());
//
//            // 保存完整的日期信息（每天只保存一次）
//            if (!dailyMetaData.containsKey(key)) {
//                Map<String, Object> metaData = new HashMap<>();
//                metaData.put("year", dataYear);
//                metaData.put("month", month);
//                metaData.put("day", day);
//                metaData.put("date", data.get("date"));
//                dailyMetaData.put(key, metaData);
//            }
//
//            // 如果同一天同一个类型有多条记录，累加价格（虽然SQL已经做了SUM，但这里保持逻辑完整性）
//            dailyDataMap.get(key).merge(priceType, totalPrice != null ? totalPrice : BigDecimal.ZERO,
//                    BigDecimal::add);
//        }
//
//        // 构建返回结果
//        List<NeWestElectricPriceVO> resultList = new ArrayList<>();
//
//        for (Map.Entry<String, Map<Byte, BigDecimal>> entry : dailyDataMap.entrySet()) {
//            Map<String, Object> metaData = dailyMetaData.get(entry.getKey());
//            if (metaData == null) continue;
//
//            NeWestElectricPriceVO vo = new NeWestElectricPriceVO();
//            vo.setYear((Integer) metaData.get("year"));
//            vo.setMonth((Integer) metaData.get("month"));
//            vo.setDay((Integer) metaData.get("day"));
//            vo.setDate((Date) metaData.get("date"));
//
//            Map<Byte, BigDecimal> priceMap = entry.getValue();
//            // 设置常规补贴价（price_type = 0）
//            vo.setSubsidyPrice(priceMap.get((byte) 0));
//            // 设置平价（price_type = 1）
//            vo.setFlatPrice(priceMap.get((byte) 1));
//            // 设置其他价格（price_type = 2）
//            vo.setOtherPrice(priceMap.get((byte) 2));
//
//            resultList.add(vo);
        }
        
        // 按年份、月份和日期排序
        resultList.sort(Comparator.comparing(NeWestElectricPriceVO::getYear)
                .thenComparing(NeWestElectricPriceVO::getMonth)
                .thenComparing(NeWestElectricPriceVO::getDay));
        
        return resultList;
    }
}
